import './ClassManagement.scss';

import { useState, useEffect } from 'react';
import {
  Button,
  Breadcrumb,
  Form,
  Input,
  Table,
  Drawer,
  Modal,
  message,
  Select,
} from 'antd';
import { SearchOutlined, DoubleRightOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  getClass,
  addClass,
  delClass,
  editClass,
} from '../../../../apis/data/classManagementAPI';

const ClassManagement: React.FC = () => {
  const [page, setPage] = useState(1);
  const [count, setCount] = useState(5);
  const [total, setTotal] = useState(0);
  const [search, setSearch] = useState('');
  const [data, setData] = useState<DataType[]>([]);
  const [delId, setDelId] = useState<React.Key[]>([]);
  const [editData, setEditData] = useState<DataType[]>([]);

  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [addOpen, setAddOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [delModalOpen, setDelModalOpen] = useState(false);
  interface DataType {
    key: React.Key;
    c_id: number;
    g_grade: string;
    c_class: string;
    number: number;
  }

  const columns: ColumnsType<DataType> = [
    {
      title: '年级',
      dataIndex: 'g_grade',
    },
    {
      title: '班级',
      dataIndex: 'c_class',
    },
    {
      title: '学生数',
      dataIndex: 'number',
    },
  ];

  // rowSelection object indicates the need for row selection
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        'selectedRows: ',
        selectedRows
      );
      setDelId(selectedRowKeys);
      setEditData(selectedRows);
    },
  };
  //render
  const getData = () => {
    getClass({ search: search, page: page, count: count }).then((res: any) => {
      setTotal(res.total);
      if (res.error === 0) {
        let _data = res.data.map((v: any) => {
          return { ...v, key: v.c_id };
        });
        setData(_data);
      } else {
        message.error('数据获取失败');
      }
    });
  };

  //init
  useEffect(() => {
    getData();
  }, [page, count, total, search]);
  //search
  const onSearch = (value: any) => {
    setSearch(value.search);
  };
  //reset
  const onReset = () => {
    setSearch('');
    setPage(1);
    form.resetFields();
  };
  //pagination
  const onChangeFn = (page: number, pageSize: number) => {
    setPage(page);
    setCount(pageSize);
  };
  //add
  const onAdd = (value: any) => {
    console.log(value);
    addClass(value).then((res: any) => {
      if (res.error === 0) {
        getData();
        message.success('添加成功');
      } else {
        message.error('添加失败');
      }
    });
  };

  //edit
  const showModal = () => {
    if (editData.length === 0) return;
    setEditOpen(true);
    let data = {
      grade: editData[0].g_grade,
      className: editData[0].c_class,
    };
    editForm.setFieldsValue(data);
  };
  const onEdit = (value: any) => {
    editClass({ id: editData[0].c_id, className: value.className }).then(
      (res: any) => {
        if (res.error === 0) {
          message.success('修改成功');
          getData();
          setEditOpen(false);
        } else {
          message.error('修改失败');
        }
      }
    );
  };
  //delete
  const onDel = () => {
    delClass({ id: delId[0] }).then((res: any) => {
      if (res.error === 0) {
        message.success('删除成功');
        getData();
        setDelModalOpen(false);
      } else {
        message.error('删除失败');
      }
    });
  };
  //advanced search
  const showDrawer = () => {
    setOpen(true);
  };
  const onClose = () => {
    setOpen(false);
  };
  const onFinish = () => {};

  return (
    <div className="container">
      <div className="class">
        <Breadcrumb separator=">">
          <Breadcrumb.Item>
            <Button type="link" style={{ color: '#333' }}>
              数据管理
            </Button>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <Button type="link" style={{ color: '#333' }}>
              班级管理
            </Button>
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="header-box">
          <div className="operation-box">
            <Button
              type="primary"
              style={{ background: '#69657e' }}
              onClick={() => {
                setAddOpen(true);
              }}
            >
              新增
            </Button>
            <Button
              type="primary"
              style={{ background: '#69657e' }}
              onClick={showModal}
            >
              修改
            </Button>
            <Button
              type="primary"
              style={{ background: '#69657e' }}
              onClick={() => {
                setDelModalOpen(true);
              }}
            >
              删除
            </Button>
          </div>
          <div className="search-box">
            <Form
              form={form}
              name="control-hooks"
              layout="inline"
              onFinish={onSearch}
            >
              <Form.Item name="search">
                <Input placeholder="请输入班级" />
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  style={{ background: '#69657e' }}
                  htmlType="submit"
                  onClick={onSearch}
                >
                  <SearchOutlined />
                </Button>
                <Button
                  type="primary"
                  style={{ background: '#69657e' }}
                  onClick={onReset}
                >
                  重置
                </Button>
              </Form.Item>
            </Form>
            <Button type="link" onClick={showDrawer}>
              高级筛选
              <DoubleRightOutlined rotate={90} style={{ color: '#d4d2d2' }} />
            </Button>
          </div>
        </div>

        <Table
          bordered={true}
          rowSelection={{
            type: 'radio',
            ...rowSelection,
          }}
          columns={columns}
          dataSource={data}
          pagination={{
            defaultPageSize: 5,
            defaultCurrent: 1,
            total: total,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: [5, 10, 15, 20],
            position: ['bottomLeft'],
            onChange: onChangeFn,
          }}
        />
      </div>

      <div className="drawer">
        <Drawer
          title="高级筛选"
          style={{ marginLeft: '300px', marginTop: '200px', width: '82%' }}
          placement="top"
          height={200}
          closable={true}
          onClose={onClose}
          open={open}
          getContainer={() => document.querySelector('.header-box')!}
        >
          <Form
            layout="inline"
            name="highSearch"
            initialValues={{ remember: true }}
            onFinish={onFinish}
            autoComplete="off"
          >
            <Form.Item label="年级" name="grade">
              <Input placeholder="请输入年级" />
            </Form.Item>

            <Form.Item label="班级" name="class">
              <Input placeholder="请输入班级" />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                style={{ background: '#69657e' }}
                htmlType="submit"
              >
                查询
              </Button>
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                style={{ background: '#69657e' }}
                onClick={onReset}
              >
                重置
              </Button>
            </Form.Item>
          </Form>
        </Drawer>
      </div>
      {/* 新增 */}
      <Modal
        title="班级管理-新增"
        centered
        open={addOpen}
        onOk={onAdd}
        onCancel={() => setAddOpen(false)}
        width={1280}
        destroyOnClose={true}
        footer={null}
      >
        <Form
          name="addData"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 8 }}
          autoComplete="off"
          onFinish={onAdd}
        >
          <Form.Item label="年级名称" name="grade">
            <Select
              placeholder="请选择"
              options={[
                { value: 1, label: '一年级' },
                { value: 2, label: '二年级' },
                { value: 3, label: '三年级' },
                { value: 4, label: '四年级' },
                { value: 5, label: '五年级' },
                { value: 6, label: '六年级' },
              ]}
            />
          </Form.Item>
          <Form.Item label="班级名称" name="className">
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item label=" ">
            <Button
              type="primary"
              style={{ background: '#69657e' }}
              htmlType="submit"
            >
              添加
            </Button>
            <Button
              type="primary"
              style={{ background: '#69657e', marginLeft: '200px' }}
              onClick={() => {
                setAddOpen(false);
              }}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改 */}
      <Modal
        title="班级管理-新增"
        centered
        open={editOpen}
        onCancel={() => setEditOpen(false)}
        width={1280}
        destroyOnClose={true}
        footer={null}
        forceRender
      >
        <Form
          form={editForm}
          name="editData"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 8 }}
          autoComplete="off"
          onFinish={onEdit}
        >
          <Form.Item label="年级名称" name="grade">
            <Select
              placeholder="请选择"
              disabled
              options={[
                { value: 1, label: '一年级' },
                { value: 2, label: '二年级' },
                { value: 3, label: '三年级' },
                { value: 4, label: '四年级' },
                { value: 5, label: '五年级' },
                { value: 6, label: '六年级' },
              ]}
            />
          </Form.Item>
          <Form.Item label="班级名称" name="className">
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item label=" ">
            <Button
              type="primary"
              style={{ background: '#69657e' }}
              htmlType="submit"
            >
              修改
            </Button>
            <Button
              type="primary"
              style={{ background: '#69657e', marginLeft: '200px' }}
              onClick={() => {
                setEditOpen(false);
              }}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 删除 */}
      <Modal
        title="提示"
        open={delModalOpen}
        onOk={onDel}
        onCancel={() => {
          setDelModalOpen(false);
        }}
      >
        <p>确定要删除选中班级吗？</p>
      </Modal>
    </div>
  );
};

export default ClassManagement;
